<script setup lang="ts">
import data from "~/components/backend/menu.json";
import AntdIcons from "~/components/common/icons";
import {useLocaleLocation} from "#i18n";
import {useBackendAccessToken, usePermissions} from "~/composables/state";
import {ApiCheckLogin} from "~/api/auth";
const selected_menu = ref<any[]>([])
let open_keys = reactive<any[]>([])
let localed_location = useLocaleLocation()
const router = useRouter()
const {t} = useI18n()

const permissions = usePermissions()
const route = useRoute()

function prepare_menu(){

  let temp_selected_menu:any[] = []
  let temp_open_keys:any[] = []

  const menuRecurse = (value: any) =>{
    if(value.icon_name){
      value.icon = ()=>h(AntdIcons[value.icon_name])
    }
    value.label = t(value.label)
    if(localed_location(value.url).path === localed_location(route.path).path){
      temp_selected_menu.push(value.key)
    }
    if(value.children){
      value.children = value.children.filter(menuRecurse)
      if(!value.children || value.children.length === 0){
        return false;
      }
      if(value.default_open){
        temp_open_keys.push(value.key)
      }
    }
    if(!value.permissions){
      return true;
    }

    if(!permissions.value){
      return false;
    }
    for(let permission in value.permissions){
      if(!permissions.value[value.permissions[permission]]) return false;
    }
    return true;
  }

  open_keys = temp_open_keys
  selected_menu.value = temp_selected_menu
  return data.filter(menuRecurse)
}

let menu_clicked = (item: any)=>{
  selected_menu.value = [item.key]
  router.push(localed_location(item.item.url))
}
const access_token = useBackendAccessToken()
let menu_data = ref([])

if(!access_token.value){
  router.push(localed_location("/backend/login"))
} else {
  ApiCheckLogin().then((res)=>{
    let temp_permissions = []
    for(let permission of res.data.data){
      temp_permissions[permission] = true
    }
    permissions.value = temp_permissions
    menu_data = prepare_menu()
  }).catch((err)=>{
    console.log("ERR", err)
  })

}

</script>

<template>
  <a-menu mode="inline" theme="dark" :items="menu_data" v-model:selectedKeys="selected_menu" v-model:openKeys="open_keys" @click="menu_clicked"/>
</template>

<style scoped>

</style>
